package servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import service.ActorService;
import service.UserService;
import domain.User;
import ex.PasswordChangeFailedException;

public class ChangePassword extends HttpServlet {
	UserService userService = new UserService();
	ActorService actorService = new ActorService();

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher = request
				.getRequestDispatcher("jsp/user/change-password.jsp");
		if (dispatcher != null)
			dispatcher.forward(request, response);
	}

	protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
		try{
			String oldPassword = request.getParameter("oldPassword");
			String newPassword1 = request.getParameter("newPassword1");
			String newPassword2 = request.getParameter("newPassword2");
	
			HttpSession session = request.getSession();
			if (session.getAttribute("user") != null) {
				User user = (User) session.getAttribute("user");
				if(user!=null){	
					if (user.getPassword().equals(oldPassword)) {
						if (newPassword1.length() > 7 && newPassword1.length() < 17) {
							if(newPassword1.equals(newPassword2)){//allow the edit, everything matches
								user.setPassword(newPassword1);
								userService.updateUser(user);
								response.sendRedirect("user?who=me");
							}else{//Password1 and Password2 do not match
								throw new PasswordChangeFailedException("New password does not match");
							}
						}else{//password should be at least 8 at most 16 chars
							throw new PasswordChangeFailedException("Passwords should be between 8 and 16 characters long");
						}
					} else {//the old password is wrong
						throw new PasswordChangeFailedException("Wrong old password entered");
					}
				}	
			}else{
				response.sendRedirect("home");
			}
		}catch(PasswordChangeFailedException pce){
			request.setAttribute("changePasswordError", pce.getMessage());
			RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/change-password.jsp");
			if (dispatcher != null) dispatcher.forward(request, response);
		}catch (Exception e) {
			request.setAttribute("changePasswordError", "A general error occured:" + e.getMessage());
			RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/change-password.jsp");
			if (dispatcher != null) dispatcher.forward(request, response);
		}
	}

}
